#include "WiFiManager.h"
#include <Arduino.h>
#include <FastLED.h>

WiFiManager::WiFiManager(const char* defaultSSID, const char* defaultPass) {
    // 保存默认凭据
    strncpy(this->defaultSSID, defaultSSID, sizeof(this->defaultSSID)-1);
    this->defaultSSID[sizeof(this->defaultSSID)-1] = '\0';
    
    strncpy(this->defaultPass, defaultPass, sizeof(this->defaultPass)-1);
    this->defaultPass[sizeof(this->defaultPass)-1] = '\0';
    
    EEPROM.begin(EEPROM_SIZE);
    loadCredentials();
}

void WiFiManager::begin() {
    Serial.println("开始WiFi连接流程");
    
    // 首先尝试使用保存的凭据连接
    if (strlen(ssid) > 0) {
        Serial.printf("尝试使用保存的凭据连接: %s\n", ssid);
        connectToWiFi(ssid, password);
        
        if (isConnected()) {
            apModeActive = false;
            return;
        }
    }
    
    // 保存的凭据失败，尝试默认凭据
    Serial.printf("尝试使用默认凭据连接: %s\n", defaultSSID);
    connectToWiFi(defaultSSID, defaultPass);
    
    if (isConnected()) {
        apModeActive = false;
        // 保存默认凭据到EEPROM
        strncpy(ssid, defaultSSID, sizeof(ssid));
        strncpy(password, defaultPass, sizeof(password));
        saveCredentials();
        return;
    }
    
    // 所有尝试失败后进入AP模式
    Serial.println("所有连接尝试失败，启动AP模式...");
    WiFi.softAP("ESP32_Clock", "12345678");
    apModeActive = true;
}

void WiFiManager::connectToWiFi(const char* ssidToConnect, const char* passToConnect) {
    WiFi.disconnect(true);
    delay(1000);
    WiFi.mode(WIFI_STA);
    
    // 使用DHCP代替静态IP
    WiFi.config(INADDR_NONE, INADDR_NONE, INADDR_NONE, INADDR_NONE);
    
    Serial.printf("连接至: %s\n", ssidToConnect);
    WiFi.begin(ssidToConnect, passToConnect);
    
    unsigned long startTime = millis();
    
    // 延长超时时间至30秒
    while (WiFi.status() != WL_CONNECTED && millis() - startTime < 30000) {
        delay(500);
        Serial.print(".");
    }
    
    if (WiFi.status() == WL_CONNECTED) {
        Serial.println("\n连接成功!");
        Serial.print("IP地址: ");
        Serial.println(WiFi.localIP());
    } else {
        Serial.println("\n连接失败!");
    }
}

bool WiFiManager::isConnected() { 
    return WiFi.status() == WL_CONNECTED; 
}

void WiFiManager::attemptReconnect() {
    if (!isConnected() && !apModeActive) {
        Serial.println("尝试重新连接WiFi...");
        connectToWiFi(ssid, password);
    }
}

void WiFiManager::loadCredentials() {
    // 检查EEPROM是否初始化
    if (EEPROM.read(0) == 0xFF && EEPROM.read(1) == 0xFF) {
        Serial.println("EEPROM未初始化，使用默认凭据");
        return;
    }
    
    for (int i = 0; i < 32; i++) ssid[i] = EEPROM.read(i);
    ssid[32] = '\0';
    
    for (int i = 0; i < 64; i++) password[i] = EEPROM.read(32 + i);
    password[64] = '\0';
    
    Serial.printf("从EEPROM加载凭据: SSID=%s\n", ssid);
}

void WiFiManager::saveCredentials() {
    for (int i = 0; i < 32; i++) EEPROM.write(i, ssid[i]);
    for (int i = 0; i < 64; i++) EEPROM.write(32 + i, password[i]);
    EEPROM.commit();
    Serial.printf("保存凭据到EEPROM: SSID=%s\n", ssid);
}

void WiFiManager::resetCredentials() {
    for (int i = 0; i < 96; i++) EEPROM.write(i, 0);
    EEPROM.commit();
    Serial.println("重置EEPROM中的凭据");
}

void WiFiManager::saveConfig(const DeviceConfig& config) {
    uint8_t* ptr = (uint8_t*)&config;
    for (int i = 0; i < sizeof(DeviceConfig); i++) {
        EEPROM.write(CONFIG_OFFSET + i, ptr[i]);
    }
    EEPROM.commit();
    Serial.println("保存配置到EEPROM");
}

void WiFiManager::loadConfig(DeviceConfig& config) {
    DeviceConfig loaded;
    uint8_t* ptr = (uint8_t*)&loaded;
    
    for (int i = 0; i < sizeof(DeviceConfig); i++) {
        ptr[i] = EEPROM.read(CONFIG_OFFSET + i);
    }
    
    // 验证配置有效性
    if (loaded.brightness < 10 || loaded.brightness > 255) {
        Serial.println("使用默认配置");
        config = defaultConfig;
    } else {
        Serial.println("使用保存的配置");
        config = loaded;
    }
}

void WiFiManager::resetConfig() {
    for (int i = 0; i < sizeof(DeviceConfig); i++) {
        EEPROM.write(CONFIG_OFFSET + i, 0);
    }
    EEPROM.commit();
    Serial.println("重置显示配置");
}